import { Blog } from '../model/Blog.js'
import { Op } from 'sequelize'

let fn_list = async (ctx, next) => {

    /*
      1.获取数据
      2.处理数据
      3.返回响应

  */
    // 通过查询字符串的方式，获取关键字，如果有传，则根据关键字过滤，如果无，则返回所有数据
    // 判断关键字有没有，数据库查询作处理
    // 返回最后结果
    let keyword = ctx.request.query.keyword || ''

    let where = null
    if (keyword.trim()) {
        where={
            [Op.or]:{
                title:{
                    [Op.like]:`%${keyword}%`
                },
                author:{
                    [Op.like]:`%${keyword}%`
                }
            }
        }
    }


    let blogs = await Blog.findAll({where})
    //    console.log(blogs);   
    ctx.body = {
        code: 1000,
        msg: '博客列表',
        data: blogs
    }
}
let fn_ById = async (ctx, next) => {
    let id = ctx.params.id || 0;
    let blogs = await Blog.findByPk(id)

    ctx.body = {
        code: 1000,
        msg: '请求成功',
        data: blogs
    }
}
let fn_add = async (ctx, next) => {
    let obj = ctx.request.body
    let blogs = await Blog.create(obj)

    ctx.body = {
        code: 1000,
        msg: '新增成功',
        data: blogs
    }
}
let fn_Edit = async (ctx, next) => {
    let id = ctx.params.id || 0
    let obj = ctx.request.body

    let blogs = await Blog.update(obj, {
        where: {
            id: id
        }
    })

    ctx.body = {
        code: 1000,
        msg: '修改成功',
        data: blogs
    }
}
let fn_Delete = async (ctx, next) => {
    let id = ctx.params.id || 0;
    await Blog.destroy({
        where: {
            id: id
        }
    })
    console.log(id);

    ctx.body = {
        code: 1000,
        msg: '删除成功',
        data: null
    }
}


export const obj = {
    "get /blogs": fn_list,
    "get /blogs/:id": fn_ById,
    "post /blogs": fn_add,
    "put /blogs/:id": fn_Edit,
    "delete /blogs/:id": fn_Delete
}